package at.jku.pervasive.gui.model;

import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.swing.table.AbstractTableModel;

import at.jku.pervasive.Position;

public class RecentTagsTableModel extends AbstractTableModel
{

	private LinkedList<Position> tagPositions;
	private final String[] columns;
	private final int numberOfRecentTagPositions;

	public RecentTagsTableModel(int numberOfRecentTagPositions)
	{
		super();

		// this.numberOfRecentTagPositions = numberOfRecentTagPositions;
		this.numberOfRecentTagPositions = -1;

		this.columns = new String[] { "Tag-ID", "X", "Y", "Z", "last seen" };
		this.tagPositions = new LinkedList<Position>();
	}

	public int getColumnCount()
	{
		return this.columns.length;
	}

	@Override
	public String getColumnName(int column)
	{
		return this.columns[column];
	}

	public int getRowCount()
	{
		return tagPositions.size();
	}

	@Override
	public Class<?> getColumnClass(int columnIndex)
	{
		switch (columnIndex)
		{
			case 0:
				return String.class;
			case 1:
			case 2:
			case 3:
				return Double.class;
			case 4:
				return Date.class;
		}
		return Object.class;
	}

	public void addTagPosition(Position newPosition)
	{
		this.tagPositions.addFirst(newPosition);
		if (numberOfRecentTagPositions != -1 && this.tagPositions.size() >= numberOfRecentTagPositions)
			this.tagPositions.removeLast();

		fireTableDataChanged();
	}

	public Object getValueAt(int rowIndex, int columnIndex)
	{
		Position position = this.tagPositions.get(rowIndex);
		switch (columnIndex)
		{
			case 0:
				return position.getId();
			case 1:
				return position.getX();
			case 2:
				return position.getY();
			case 3:
				return position.getZ();
			case 4:
				return position.getDate();
		}
		return null;
	}

	public void clearAllTagPositions()
	{
		this.tagPositions.clear();
		fireTableDataChanged();
	}

	public Map<String, List<Position>> getPositions(int[] indices)
	{
		Map<String, List<Position>> tagPositionsMap = new TreeMap<String, List<Position>>();
		for (int index : indices)
		{
			Position pos = this.tagPositions.get(index);
			String tagId = pos.getId();
			List<Position> list = tagPositionsMap.get(tagId);
			if (list != null)
			{
				list.add(pos);
			}
			else
			{
				list = new LinkedList<Position>();
				list.add(pos);
				tagPositionsMap.put(tagId, list);
			}
		}
		return tagPositionsMap;
	}

	public void setTagPositions(Position[] positions)
	{
		tagPositions.clear();
		tagPositions.addAll(Arrays.asList(positions));
		
		fireTableDataChanged();
	}
}
